package controllers

import (
	"time"
	"web/datasource"
	"web/models"

	"github.com/kataras/iris/v12"
)

type UserController struct {
	entry string
}

var db = datasource.GetDB()
var entry = "User"

func NewUserController() *UserController {
	return &UserController{entry}
}

// user
func (c *UserController) Get() interface{} {
	return iris.Map{
		"entry": entry,
		"time":  time.Now().Format("2006-01-02 15:04:05")} //固定格式
}

// user/list
func (c *UserController) GetList() interface{} {
	users := new([]models.User)
	db.Find(users)
	return iris.Map{
		"entry":  entry,
		"result": users}
}

// user/id/{id}
func (c *UserController) GetIdBy(id uint) interface{} {
	if id < 1 {
		return iris.Map{
			"entry":  entry,
			"result": "error"}
	} else {
		user := new(models.User) // new 返回指针,make 返回值
		db.First(user, id)
		return iris.Map{
			"entry":  entry,
			"result": user}
	}
}

// user/name/{name}
func (c *UserController) GetNameBy(name string) interface{} {
	users := new([]models.User)
	db.Where("name LIKE ?", "%"+name+"%").Find(users)
	return iris.Map{
		"entry":  entry,
		"result": users}
}

// PUT user/{id}
func (c *UserController) PutIdBy(ctx iris.Context) interface{} {
	user := new(models.User)
	if err := ctx.ReadJSON(user); err != nil {
		return iris.Map{
			"entry":  entry,
			"result": "error"}
	} else {
		db.Save(user)
		return iris.Map{
			"entry":  entry,
			"result": 1}
	}
}

// POST user/add
func (c *UserController) PostAdd(ctx iris.Context) interface{} {
	user := new(models.User)
	if err := ctx.ReadJSON(user); err != nil {
		return iris.Map{
			"entry":  entry,
			"result": "error"}
	} else {
		db.Create(user)
		return iris.Map{
			"entry":  entry,
			"result": 1}
	}
}

// DELETE user/id
func (c *UserController) DeleteIdBy(id uint) interface{} {
	if id < 1 {
		return iris.Map{
			"entry":  entry,
			"result": "error"}
	} else {
		user := new(models.User)
		db.First(user, id)
		if user.ID < 1 || user == nil {
			return iris.Map{
				"entry":  entry,
				"result": "error"}
		} else {
			db.Delete(user)
			return iris.Map{
				"entry":  entry,
				"result": 0}
		}
	}
}
